package com.byb.server.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.CrowdService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.byb.server.service.dto.CrowdDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Crowd.
 */
@RestController
@RequestMapping("/api")
public class CrowdResource {

    private final Logger log = LoggerFactory.getLogger(CrowdResource.class);

    private static final String ENTITY_NAME = "crowd";

    private final CrowdService crowdService;

    public CrowdResource(CrowdService crowdService) {
        this.crowdService = crowdService;
    }

    /**
     * POST  /crowds : Create a new crowd.
     *
     * @param crowdDTO the crowdDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new crowdDTO, or with status 400 (Bad Request) if the crowd has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/crowds")
    @Timed
    public ResponseEntity<CrowdDTO> createCrowd(@RequestBody CrowdDTO crowdDTO) throws URISyntaxException {
        log.debug("REST request to save Crowd : {}", crowdDTO);
        if (crowdDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new crowd cannot already have an ID")).body(null);
        }
        CrowdDTO result = crowdService.save(crowdDTO);
        return ResponseEntity.created(new URI("/api/crowds/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /crowds : Updates an existing crowd.
     *
     * @param crowdDTO the crowdDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated crowdDTO,
     * or with status 400 (Bad Request) if the crowdDTO is not valid,
     * or with status 500 (Internal Server Error) if the crowdDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/crowds")
    @Timed
    public ResponseEntity<CrowdDTO> updateCrowd(@RequestBody CrowdDTO crowdDTO) throws URISyntaxException {
        log.debug("REST request to update Crowd : {}", crowdDTO);
        if (crowdDTO.getId() == null) {
            return createCrowd(crowdDTO);
        }
        CrowdDTO result = crowdService.save(crowdDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, crowdDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /crowds : get all the crowds.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of crowds in body
     */
    @GetMapping("/crowds")
    @Timed
    public ResponseEntity<List<CrowdDTO>> getAllCrowds(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Crowds");
        Page<CrowdDTO> page = crowdService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/crowds");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /crowds/:id : get the "id" crowd.
     *
     * @param id the id of the crowdDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the crowdDTO, or with status 404 (Not Found)
     */
    @GetMapping("/crowds/{id}")
    @Timed
    public ResponseEntity<CrowdDTO> getCrowd(@PathVariable Long id) {
        log.debug("REST request to get Crowd : {}", id);
        CrowdDTO crowdDTO = crowdService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(crowdDTO));
    }

    /**
     * DELETE  /crowds/:id : delete the "id" crowd.
     *
     * @param id the id of the crowdDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/crowds/{id}")
    @Timed
    public ResponseEntity<Void> deleteCrowd(@PathVariable Long id) {
        log.debug("REST request to delete Crowd : {}", id);
        crowdService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/crowds?query=:query : search for the crowd corresponding
     * to the query.
     *
     * @param query the query of the crowd search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/crowds")
    @Timed
    public ResponseEntity<List<CrowdDTO>> searchCrowds(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of Crowds for query {}", query);
        Page<CrowdDTO> page = crowdService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/crowds");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


    /**
     * GET  /crowds/:id : get the "id" crowd.
     *
     * @param id the id of the crowdDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the crowdDTO, or with status 404 (Not Found)
     */
    @GetMapping("/crowds-by-productId/{id}")
    @Timed
    public ResponseEntity<CrowdDTO> getByProductId(@PathVariable Long id) {
        log.debug("REST request to get Crowd : {}", id);
        CrowdDTO crowdDTO = crowdService.getByProductId(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(crowdDTO));
    }


}
